<template>
  <div>
    <template slot="title">
      <BreakSpace label="工单信息"></BreakSpace>
    </template>
    <TopFilter :list="topFilterList" :cols="3" :collapse="false" :labelWidth="100" :isSubmitBtn="false"></TopFilter>
    <div :style="{ paddingLeft: '10px', minHeight: '200px', paddingBottom: '30px' }">
      <LazyLoadTab v-model="repairActiveName" :tabMenus="repairMenus" @tab-click="tabClickHandle"></LazyLoadTab>
    </div>

    <!-- <el-collapse>
      <el-collapse-item name="1">
        <template slot="title">
          <BreakSpace label="客户信息"></BreakSpace>
        </template>
        <TopFilter :list="customerList" :cols="3" :collapse="false" :labelWidth="100" :isSubmitBtn="false"></TopFilter>
      </el-collapse-item>
      <el-collapse-item name="2">
        <template slot="title">
          <BreakSpace label="车辆信息"></BreakSpace>
        </template>
        <TopFilter :list="vehicleList" :cols="3" :collapse="false" :labelWidth="100" :isSubmitBtn="false"></TopFilter>
      </el-collapse-item>
      <el-collapse-item name="3">
        <template slot="title">
          <BreakSpace label="工单信息"></BreakSpace>
        </template>
        <TopFilter :list="topFilterList" :cols="3" :collapse="false" :labelWidth="100" :isSubmitBtn="false"></TopFilter>
        <FormPanel :list="orderAmountList" :labelWidth="120" :isSubmitBtn="false"></FormPanel>
      </el-collapse-item>
      <el-collapse-item name="4">
        <template slot="title">
          <BreakSpace label="结算单信息"></BreakSpace>
        </template>
        <TopFilter :list="bottomFilterList" :cols="3" :collapse="false" :labelWidth="100" :isSubmitBtn="false"></TopFilter>
      </el-collapse-item>
    </el-collapse> -->

    <BaseDialog title="收费类别" :visible.sync="PrintDialogShow" :width="'40%'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <printOrder
        :roNo="roNo"
        @close="
          val => {
            this.PrintDialogShow = val;
          }
        "
      />
    </BaseDialog>
    <BaseDialog title="打印结算单" :visible.sync="prePrintDialogShow" :width="'40%'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <printBalance
        :printBalanceData="printBalanceData"
        @close="
          val => {
            this.prePrintDialogShow = val;
          }
        "
      />
    </BaseDialog>

    <ButtonArea
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
        justifyContent: 'flex-end'
      }"
    >
      <!-- <el-button type="primary" icon="el-icon-printer" :disabled="isPrint" @click="printOrderClick">打印工单</el-button> -->
      <!-- <el-button v-if="isShow" type="primary" icon="el-icon-printer" :disabled="isPrintJS" @click="printBalanceClick">打印结算单</el-button> -->
      <printRepairOrder :roNo="list.RO_NO" />
      <printBallanceOrder v-if="isShow" btnText="打印结算单" :roNo="list.RO_NO" />
      <el-button @click="closeDialog">取消</el-button>
      <div v-if="printShow">
        <BasePrint ref="print" :data="printList" :showForwardText="orderPrintShowForwardText" template="templatePrintFee" />
      </div>
    </ButtonArea>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
import QRcode from 'qrcode';
import { Tag } from 'element-ui';
import moment from 'moment';
import { constants } from 'crypto';
import { queryDetailed, queryPayObj, queryBlalanceInfo } from '@/api/repair/repairReception/repairBusinessManger';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import { getInvoiceType } from '@/api/finance/repair/receivables';
import { getAllUser } from '@/api/finance/advancesReceived/register';
import { getRepairOrderPrintInfo, getWxlxSelect } from '@/api/repair/repairReception/customer';
import { queryPrintData, getRepairTypes, getAdviceLabour, getAdvicePart, getDealerCompanyByCode, getlistAllData, getOwnerAndVehicleByRoNo } from '@/api/repair/repairReception/feesSettlement';
import { getSeries, getModel } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import printBalance from './printBalance';
import printOrder from './printRo';
import { getUserInfoByRole, getUserInfo } from '@/api/customerCare/saleVisit/careTaskSearch';
import { getColorList } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import { queryFdUploadStatusByRoNo } from '@/api/repair/repairReception/customer';
import printRepairOrder from '../customer/printRepairOrder';
import printBallanceOrder from '../feesSettlement/printBallanceOrder';

export default {
  name: 'labourModel',
  components: {
    printBalance,
    printOrder,
    printRepairOrder,
    printBallanceOrder
  },
  mixins: [dictionary],
  props: ['list', 'repairParams'],
  data() {
    this.isDisabled = true;
    return {
      printShow: false,
      topFilterList: this.createTopFilterList(),
      customerList: this.createCustomerList(),
      vehicleList: this.createVehicleList(),
      repairActiveName: '维修项目',
      repairMenus: this.createRepairMenus(),
      bottomFilterList: this.createBottomFilterList(),
      orderAmountList: this.createOrderAmountList(),
      isShow: this.isShows(),
      isPrint: true,
      isPrintJS: true,
      printBalanceData: [],
      isBalanceShow: false,
      prePrintDialogShow: false, // 结算单
      PrintDialogShow: false, // 工单
      printOrderData: [],
      roNo: null,
      printList: {} // 打印数据
    };
  },
  computed: {
    orderPrintShowForwardText() {
      return this.printList.repairOrderMainInfo && this.printList.repairOrderMainInfo.BOOKING_ORDER_NO ? true : false;
    }
  },
  mounted() {
    this.serviceConsultant();
    this.getWxtypeSelect();
    this.queryDetail(); // 明细查询
    this.getInvoiceTypeSelect();
    this.getOwnerAndVehicle(); // 获取车主车辆信息
    // this.getColorList();
    // this.getRepairTypesFun();
  },
  methods: {
    createVehicleList() {
      return [
        {
          type: 'INPUT',
          label: '牌照号',
          fieldName: 'LICENSE',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '底盘号',
          fieldName: 'VIN',
          disabled: this.isDisabled
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'MODEL',
          itemList: [],
          disabled: this.isDisabled
        },
        {
          type: 'SELECT',
          label: '客户级别',
          fieldName: 'CUSTOMER_LEVEL',
          itemList: this.createDictList('8103'),
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'ENGINE_NO',
          disabled: this.isDisabled
        },
        // {
        //   type: 'SELECT',
        //   label: '颜色',
        //   fieldName: 'COLOR',
        //   itemList: [],
        //   disabled: this.isDisabled
        // },
        {
          type: 'INPUT',
          label: '颜色',
          fieldName: 'COLOR_NAME',
          disabled: this.isDisabled
        },
        {
          type: 'SELECT',
          label: '车辆类别',
          fieldName: 'VEHICLE_CATEGORY',
          itemList: this.createDictList('8026'),
          disabled: this.isDisabled
        },
        {
          type: 'DATE',
          label: '生产日期',
          fieldName: 'PRODUCT_DATE',
          disabled: this.isDisabled
        },
        {
          type: 'DATE',
          label: '购车日期',
          fieldName: 'SALES_DATE',
          disabled: this.isDisabled,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          type: 'DATE',
          label: '发牌日期',
          fieldName: 'LISENCING_DATE',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '专属服务顾问',
          fieldName: 'SERVICE_ADVISOR',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '保险单号',
          fieldName: 'INSURANCE_BILL_NO',
          disabled: this.isDisabled
        },
        {
          type: 'SELECT',
          label: '保险公司',
          fieldName: 'INSURATION_CODE',
          disabled: this.isDisabled,
          initialValue: '',
          itemList: this.createDictList(9607)
        },
        {
          type: 'DATE',
          label: '保险起始时间',
          fieldName: 'INSURANCE_BEGIN_DATE',
          disabled: this.isDisabled
        },
        {
          type: 'DATE',
          label: '保险截止日期',
          fieldName: 'INSURANCE_END_DATE',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '保费总额',
          fieldName: 'INSURANCE_AMOUNT',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '被保险人',
          fieldName: 'INSURED_NAME',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '被保险人证件',
          fieldName: 'INSURED_CT',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '其他保险公司',
          fieldName: 'INSURANCE_OTHER_CODE',
          disabled: this.isDisabled,
          itemList: this.createDictList(9607)
        },
        {
          type: 'SELECT',
          label: '销售顾问',
          fieldName: 'CONSULTANT',
          itemList: [],
          disabled: this.isDisabled
        },
        {
          type: 'CHECKBOX',
          label: '二手车',
          fieldName: 'SECOND_HAND',
          options: {
            trueValue: 10041001,
            falseValue: 10041002
          },
          disabled: this.isDisabled
        },
        {
          type: 'CHECKBOX',
          label: '车损险',
          fieldName: 'INSURANCE_CSXBS',
          disabled: this.isDisabled,
          options: {
            trueValue: '10041001',
            falseValue: '10041002'
          }
        },
        {
          type: 'INPUT',
          label: '车辆备注',
          fieldName: 'REMARK',
          disabled: this.isDisabled
        }
      ];
    },

    createCustomerList() {
      return [
        {
          type: 'INPUT',
          label: '客户代码',
          fieldName: 'OWNER_NO',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'OWNER_NAME',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '身份证号码',
          fieldName: 'CERTIFICATE_NO',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '客户移动电话',
          fieldName: 'MOBILE',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '客户电话',
          fieldName: 'PHONE',
          disabled: this.isDisabled
        },
        {
          type: 'SELECT',
          label: '客户类别',
          fieldName: 'OWNER_PROPERTY',
          placeholder: '请选择...',
          itemList: this.createDictList('8011'),
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '客户地址',
          fieldName: 'ADDRESS',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '送修人姓名',
          fieldName: 'deliverer',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '送修人移动电话',
          fieldName: 'delivererMobile',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '送修人电话',
          fieldName: 'delivererPhone',
          disabled: this.isDisabled
        }
      ];
    },

    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'engineNo',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          disabled: this.isDisabled
        },
        // {
        //   type: 'SELECT',
        //   label: '工单类型',
        //   fieldName: 'roType',
        //   itemList: [],
        //   disabled: this.isDisabled
        // },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          itemList: [],
          disabled: this.isDisabled
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          itemList: [],
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '开单时间',
          fieldName: 'roCreateDate',
          disabled: this.isDisabled,
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'INPUT',
          label: '进厂里程',
          fieldName: 'inMileage',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '出厂里程',
          fieldName: 'outMileage',
          disabled: this.isDisabled
        },
        {
          type: 'DATE',
          label: '销售日期',
          fieldName: 'licenseDate',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '送修人姓名',
          fieldName: 'deliverer',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '送修人电话',
          fieldName: 'delivererPhone',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '送修人手机',
          fieldName: 'delivererMobile',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '估价单号',
          fieldName: 'estimateNo',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '预计交车时间',
          fieldName: 'endTimeSupposed',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '送修问题',
          // label: '客户描述',
          fieldName: 'customerDesc',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '检查结果',
          // label: '故障描述',
          fieldName: 'roTroubleDesc',
          disabled: this.isDisabled
        }
        // {
        //   type: 'CHECKBOX',
        //   label: '新保',
        //   fieldName: 'isXb',
        //   options: {
        //     trueValue: 10041001,
        //     falseValue: 10041002
        //   },
        //   disabled: true
        // },
        // {
        //   type: 'CHECKBOX',
        //   label: 'FD上传状态',
        //   fieldName: 'fdStatus',
        //   options: {
        //     trueValue: 10041001,
        //     falseValue: 10041002
        //   },
        //   disabled: true
        // },
        // {
        //   type: 'DATE',
        //   label: 'FD上传日期',
        //   fieldName: 'fdDate',
        //   disabled: true,
        //   placeholder: '请选择...'
        // },
        // {
        //   type: 'SELECT',
        //   label: '包工方式',
        //   palceholder: '请选择',
        //   fieldName: 'bgType',
        //   disabled: true,
        //   itemList: this.createDictList('8145')
        // },
        // {
        //   type: 'INPUT',
        //   label: '包工费',
        //   fieldName: 'bgf',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '材料服务费',
        //   fieldName: 'clfwf',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '辅材费',
        //   fieldName: 'fcf',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '施救费',
        //   fieldName: 'sjf',
        //   disabled: true
        // },
        // {
        //   type: 'SELECT',
        //   label: '处理结果',
        //   fieldName: 'dealResult',
        //   disabled: true,
        //   placeholder: '请选择...',
        //   itemList: [
        //     { text: '行动完成', value: '4' },
        //     { text: '行动不必要实施', value: 'H' },
        //     { text: '行动进站未修', value: '3' }
        //   ]
        // }
      ];
    },
    createRepairMenus() {
      let that = this;
      const roNo = that.list.RO_NO;
      return [
        {
          title: '维修项目',
          path: 'repair/repairReception/repairBusinessManger/repairTabs/repairPro',
          disabled: false,
          params: {
            dataList: [],
            roNo
          }
        },
        {
          title: '维修材料',
          path: 'repair/repairReception/repairBusinessManger/repairTabs/repairStuff',
          disabled: false,
          params: {
            dataList: [],
            roNo
          }
        },
        // {
        //   title: '预估备件',
        //   path: 'repair/repairReception/repairBusinessManger/repairTabs/repairStuffYg',
        //   disabled: false,
        //   params: {
        //     dataList: [],
        //     roNo
        //   }
        // },
        // {
        //   title: '销售材料',
        //   path: 'repair/repairReception/repairBusinessManger/repairTabs/saleStuff',
        //   disabled: false,
        //   params: {
        //     dataList: [],
        //     roNo
        //   }
        // },
        {
          title: '附加项目',
          path: 'repair/repairReception/repairBusinessManger/repairTabs/additionalPro',
          disabled: false,
          params: {
            dataList: [],
            roNo
          }
        }
        // {
        //   title: '前台领料',
        //   path: 'repair/repairReception/repairBusinessManger/repairTabs/reception',
        //   disabled: false,
        //   params: {
        //     dataList: [],
        //     roNo
        //   }
        // },
        // {
        //   title: '建议维修项目',
        //   path: 'repair/repairReception/repairBusinessManger/repairTabs/RepairProLab',
        //   disabled: false,
        //   params: {
        //     roNo
        //   }
        // }
      ];
    },

    createBottomFilterList() {
      return [
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '结算时间',
          fieldName: 'balanceTime',
          disabled: this.isDisabled
        },
        {
          type: 'INPUT',
          label: '优惠模式',
          palceholder: '请选择',
          fieldName: 'discountModeName',
          disabled: this.isDisabled
        },
        {
          type: 'SELECT',
          label: '结算员',
          palceholder: '请选择',
          fieldName: 'balanceHandler',
          disabled: this.isDisabled,
          itemList: []
        },
        {
          type: 'INPUT',
          label: '原结算单号',
          fieldName: 'lastBalanceNo',
          disabled: this.isDisabled
        },
        // {
        //   type: 'INPUT',
        //   label: '发票单号',
        //   fieldName: 'invoiceNo',
        //   disabled: this.isDisabled
        // },
        // {
        //   type: 'SELECT',
        //   label: '发票类型',
        //   palceholder: '请选择',
        //   fieldName: 'invoiceTypeCode',
        //   disabled: this.isDisabled,
        //   itemList: []
        // },
        // {
        //   type: 'SELECT',
        //   label: '支付类型',
        //   palceholder: '请选择',
        //   fieldName: 'payTypeCode',
        //   itemList: this.createDictList('8044')
        // },
        {
          type: 'INPUT_NUMBER',
          label: '应收金额',
          fieldName: 'receiveAmount',
          precision: 2,
          disabled: this.isDisabled
        },
        {
          type: 'INPUT_NUMBER',
          label: '减免金额',
          fieldName: 'derateAmount',
          precision: 2,
          disabled: this.isDisabled
        }
      ];
    },

    createOrderAmountList() {
      return [
        {
          type: 'INPUT',
          label: '优惠后工时费',
          fieldName: 'discountLabour',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '优惠后材料费',
          fieldName: 'discountMaterial',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '工料费合计',
          fieldName: 'TOTAL_PART_LABOUR_FEE',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '优惠后工料费合计',
          fieldName: 'DISCOUNT_TOTAL_PART_LABOUR_FEE',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '累计维修金额',
          fieldName: 'HISTORY_REPAIR_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '累计维修次数',
          fieldName: 'HISTORY_REPAIR_TIMES',
          disabled: true
        }
      ];
    },
    // 颜色下拉框
    async getColorList() {
      const res = await getColorList();
      console.log('颜色', res);
      this.vehicleList.find(item => item.fieldName === 'COLOR').itemList = res.data.map(x => ({ value: x.COLOR_CODE + '', text: x.COLOR_NAME }));
    },

    // 获取服务顾问
    async serviceConsultant() {
      let consultant = { role: dictCode.SERVICE_CONSULTANT }; // 服务顾问
      const consultantRes = await searchRoleByCode(consultant);
      // console.log(consultantRes);
      this.topFilterList.find(x => x.fieldName === 'serviceAdvisor').itemList = consultantRes.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      this.serviceAdvisorData = consultantRes.data.map(x => ({ text: x.employeeName, value: x.userId }));
    },

    async getOwnerAndVehicle() {
      const roNo = this.list.RO_NO;
      let consultant = { roNo: this.list.RO_NO }; // 服务顾问
      const ownerAndVehicle = await getOwnerAndVehicleByRoNo(consultant);
      let res = ownerAndVehicle.data || {};

      const models = await getModel();
      let modelsList = models.data;
      modelsList.forEach(x => {
        if (x.MODEL_ID == res.MODEL) {
          this.vehicleList.find(y => y.fieldName == 'MODEL').initialValue = x.MODEL_NAME;
        }
      });

      this.customerList.forEach(x => {
        if (x.fieldName == 'OWNER_NAME') x.initialValue = res.OWNER_NAME;
        if (x.fieldName == 'OWNER_NO') x.initialValue = res.OWNER_NO;
        if (x.fieldName == 'PHONE') x.initialValue = res.PHONE;
        if (x.fieldName == 'MOBILE') x.initialValue = res.MOBILE;
        if (x.fieldName == 'OWNER_PROPERTY') x.initialValue = res.OWNER_PROPERTY;
        if (x.fieldName == 'CONTACTOR_NAME') x.initialValue = res.CONTACTOR_NAME;
        if (x.fieldName == 'CONTACTOR_PHONE') x.initialValue = res.CONTACTOR_PHONE;
        if (x.fieldName == 'CONTACTOR_MOBILE') x.initialValue = res.CONTACTOR_MOBILE;
        if (x.fieldName == 'CERTIFICATE_NO') x.initialValue = res.CERTIFICATE_NO;
        if (x.fieldName == 'ADDRESS') x.initialValue = res.ADDRESS;
      });
      this.vehicleList.forEach(x => {
        if (x.fieldName == 'LICENSE') x.initialValue = res.LICENSE;
        if (x.fieldName == 'VIN') x.initialValue = res.VIN;
        // if(x.fieldName=="MODEL") x.initialValue = res.MODEL;
        if (x.fieldName == 'SERIES') x.initialValue = res.SERIES;
        if (x.fieldName == 'CUSTOMER_LEVEL') x.initialValue = res.CUSTOMER_LEVEL;
        if (x.fieldName == 'ENGINE_NO') x.initialValue = res.ENGINE_NO;
        if (x.fieldName == 'COLOR_NAME') x.initialValue = res.COLOR_NAME;
        if (x.fieldName == 'VEHICLE_CATEGORY') x.initialValue = res.VEHICLE_CATEGORY;
        if (x.fieldName == 'PRODUCT_DATE') x.initialValue = res.PRODUCT_DATE;
        if (x.fieldName == 'LISENCING_DATE') x.initialValue = res.LISENCING_DATE;
        if (x.fieldName == 'SECOND_HAND') x.initialValue = res.SECOND_HAND;
        if (x.fieldName == 'SERVICE_ADVISOR') x.initialValue = res.SERVICE_ADVISOR;
        if (x.fieldName == 'CONSULTANT') x.initialValue = res.CONSULTANT;
        if (x.fieldName == 'REMARK') x.initialValue = res.REMARK;
        if (x.fieldName == 'INSURATION_CODE') x.initialValue = res.INSURATION_CODE ? +res.INSURATION_CODE : '';
        if (x.fieldName == 'INSURANCE_BILL_NO') x.initialValue = res.INSURANCE_BILL_NO;
        if (x.fieldName == 'INSURANCE_BEGIN_DATE') x.initialValue = res.INSURANCE_BEGIN_DATE;
        if (x.fieldName == 'INSURANCE_END_DATE') x.initialValue = res.INSURANCE_END_DATE;
        if (x.fieldName == 'INSURED_NAME') x.initialValue = res.INSURED_NAME;
        if (x.fieldName == 'INSURED_CT') x.initialValue = res.INSURED_CT;
        if (x.fieldName == 'INSURANCE_CSXBS') x.initialValue = res.INSURANCE_CSXBS;
        if (x.fieldName == 'INSURANCE_AMOUNT') x.initialValue = res.INSURANCE_AMOUNT;
        if (x.fieldName == 'INSURANCE_OTHER_CODE') x.initialValue = res.INSURANCE_OTHER_CODE ? +res.INSURANCE_OTHER_CODE : '';
        if (x.fieldName == 'SALES_DATE') x.initialValue = res.SALES_DATE;
      });

      let consultant1 = { role: dictCode.SERVICE_CONSULTANT }; // 服务顾问
      const consultantRes = await searchRoleByCode(consultant1);
      consultantRes.data.map(x => {
        if (res.SERVICE_ADVISOR === x.userId + '') {
          this.vehicleList.find(y => y.fieldName == 'SERVICE_ADVISOR').initialValue = x.employeeName;
        }
      });

      await getUserInfo().then(res1 => {
        if (res1.resultCode == 200) {
          let param = {
            companyId: res1.data.userInfo.companyId,
            positionCode: '10061015'
          };
          getUserInfoByRole(param).then(res1 => {
            if (res1.resultCode == 200) {
              res1.data.forEach(x => {
                if (x.userId == res.CONSULTANT) {
                  this.vehicleList.find(item => item.fieldName === 'CONSULTANT').initialValue = x.employeeName;
                }
              });
            } else {
              this.$message.error('获取销售顾问列表失败!');
            }
          });
        } else {
          this.$message.error('获取当前登录用户信息失败!');
        }
      });

      console.log('==============>', ownerAndVehicle);
    },
    // 获取维修项目类型
    async getWxtypeSelect() {
      const res = await getWxlxSelect();
      // console.log('维修项目==============维修类型' + res);
      this.topFilterList.find(x => x.fieldName === 'repairTypeCode').itemList = res.data.map(x => ({
        value: x.REPAIR_TYPE_CODE + '',
        text: x.REPAIR_TYPE_NAME
      }));
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
    },
    async getInvoiceTypeSelect() {
      // const res = await getInvoiceType();
      const handRes = await getAllUser();
      console.log('111111111111111111111', handRes);
      // this.bottomFilterList.find(x => x.fieldName === 'invoiceTypeCode').itemList = res.data.map(x => ({ value: x.INVOICE_TYPE_CODE, text: x.INVOICE_TYPE_NAME }));
      this.bottomFilterList.find(x => x.fieldName === 'balanceHandler').itemList = handRes.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    // 查询工单明细
    async queryDetail() {
      const newStr = [];
      const roNo = this.list.RO_NO;
      const res = await queryDetailed(roNo);
      if (res.data) {
        this.printOrderData = res.data[0];
      }
      if (res.data) {
        for (let [key, val] of Object.entries(res.data)) {
          let param = {
            fieldName: this.camelcase(key),
            value: val
          };
          newStr.push(param);
        }
        this.syncFormListData(newStr);
        // 将送修人电话解析到对应的联系人中的信息  add by yush
        this.getDelivererInfo(newStr);
        this.vin = this.topFilterList.find(x => x.fieldName === 'vin').initialValue;
        this.printBalanceData['VIN'] = this.vin;
        this.roNo = this.topFilterList.find(x => x.fieldName === 'roNo').initialValue;

        // 前台计算工料费合计
        res.data.TOTAL_PART_LABOUR_FEE = (+res.data.PART_SALES_AMOUNT || 0) + (+res.data.LABOUR_AMOUNT_SUM || 0);
        res.data.DISCOUNT_TOTAL_PART_LABOUR_FEE = (+res.data.discountLabour || 0) + (+res.data.discountMaterial || 0);

        // 赋值新增字段信息金额字段
        this.orderAmountList.forEach(item => {
          if (res.data[item.fieldName]) {
            item.initialValue = res.data[item.fieldName];
          } else {
            item.initialValue = 0;
          }
        });
      }
    },

    // 将送修人电话解析到对应的联系人中的信息  add by yush
    async getDelivererInfo(dataList) {
      const formList = [...this.customerList];
      const formFieldNames = formList.map(x => x.fieldName);
      dataList.forEach(x => {
        if (formFieldNames.includes(x.fieldName)) {
          let target = formList.find(k => k.fieldName === x.fieldName);
          if (!target) return;
          target.initialValue = x.value;
        }
      });
    },

    // 结算单信息查询
    async queryPay() {
      let newStr = [];
      let roNo = this.list.RO_NO;
      const res = await queryBlalanceInfo(roNo);
      this.printBalanceData = res.data[0];
      this.isPrintJS = false;
      if (res.data.length) {
        for (let [key, val] of Object.entries(res.data[0])) {
          let param = {
            fieldName: this.camelcase(key),
            value: val
          };
          newStr.push(param);
        }
        let formList = [...this.bottomFilterList];
        let formFieldNames = formList.map(x => x.fieldName);
        newStr.forEach(x => {
          if (formFieldNames.includes(x.fieldName)) {
            let target = formList.find(k => k.fieldName === x.fieldName);
            if (!target) return;
            if (x.fieldName === 'receiveAmount' || x.fieldName === 'derateAmount') {
              target.initialValue = Number(x.value).toFixed(2);
            } else {
              target.initialValue = x.value;
            }
          }
        });
      }
    },
    async printBalance() {
      const roNo = this.topFilterList.find(item => item.fieldName === 'roNo').initialValue;
      console.log('66666666666666666666666', roNo);
      let res2 = getRepairOrderPrintInfo(roNo); // 获取打印主数据
      // let res3 = queryPrintData(roNo, 1); // 获取打印表头数据
      // console.log(res,'printData', res1)
      let res = await res2;
      // let res1 = await res3;
      if (res.resultCode == 200) {
        this.printList = _.cloneDeep(res.data);
        // this.printList['companyNameCn'] = res1.data.companyInfo.companyNameCn;
        // this.printList['companyNameEn'] = res1.data.companyInfo.companyNameEn;
        // this.printList['addressZh'] = res1.data.companyInfo.addressZh;
        // this.printList['addressEn'] = res1.data.companyInfo.addressEn;
        // this.printList['phone'] = res1.data.companyInfo.phone;
        // this.printList['zipCode'] = res1.data.companyInfo.zipCode;
        // this.printList['fax'] = res1.data.companyInfo.fax;
        if (this.printList.repairOrderMainInfo.RO_CREATE_DATE != '') {
          this.printList.repairOrderMainInfo.RO_CREATE_DATE = moment(this.printList.repairOrderMainInfo.RO_CREATE_DATE).format('YYYY-MM-DD HH:mm:ss');
        }
        if (this.printList.repairOrderMainInfo.END_TIME_SUPPOSED != '') {
          this.printList.repairOrderMainInfo.END_TIME_SUPPOSED = moment(this.printList.repairOrderMainInfo.END_TIME_SUPPOSED).format('YYYY-MM-DD HH:mm:ss');
        }
        let consultant = { role: dictCode.SERVICE_CONSULTANT }; // 服务顾问
        const consultantRes = await searchRoleByCode(consultant);
        consultantRes.data.map(x => {
          if (this.printList.repairOrderMainInfo.SERVICE_ADVISOR === x.userId + '') {
            this.printList.repairOrderMainInfo.SERVICE_ADVISOR = x.employeeName;
          }
        });
        let serviceMajordom = { role: dictCode.SERVE_MAJORDOM }; // 服务总监
        const serviceMajordomRes = await searchRoleByCode(serviceMajordom);
        if (serviceMajordomRes.data.length > 0) {
          this.printList.repairOrderMainInfo.SERVE_MAJORDOM = serviceMajordomRes.data[0].employeeName;
        }
        let oilRemain = this.printList.repairOrderMainInfo.OIL_REMAIN;
        const oilRes = this.createDictList('8045');

        for (var i = 0; i < oilRes.length; i++) {
          if (oilRemain === oilRes[i].value) {
            this.printList.repairOrderMainInfo.OIL_REMAIN = oilRes[i].text;
          }
        }

        let allUsers = { role: '' };
        const allUsersRes = await searchRoleByCode(allUsers);
        allUsersRes.data.map(x => {
          // if(x.dealerCode===this.printList.repairOrderMainInfo.OWNER_CODE){
          //   this.printList.companyName=x.dealerName
          // }
          if (x.userId + '' === this.printList.repairOrderMainInfo.TECHNICIAN) {
            this.printList.repairOrderMainInfo.TECHNICIAN = x.employeeName;
          }
          if (x.userId + '' === this.printList.repairOrderMainInfo.CREATED_BY) {
            this.printList.repairOrderMainInfo.CREATED_BY = x.employeeName;
          }

          for (var j = 0; j < this.printList.printRepairLabour.length; j++) {
            if (x.userId + '' === this.printList.printRepairLabour[j].TECHNICIAN) {
              this.printList.printRepairLabour[j].TECHNICIAN = x.employeeName;
            }
          }
        });
        const dealerCode = await getDealerCompanyByCode();
        this.printList.dealerAddress = dealerCode.data.address1;
        this.printList.phone = dealerCode.data.ascPhone;
        console.log(this.printList, 'printList', res.data);
        this.isPrint = false;
      }
    },
    // 点击打印工单
    async printOrderClick() {
      this.printShow = true;
      // this.PrintDialogShow = true;
      let fdRepairParams = this.repairParams['9403'];
      let repairType = this.topFilterList.find(item => item.fieldName === 'repairTypeCode').initialValue;
      let roNo = {
        roNo: this.topFilterList.find(item => item.fieldName === 'roNo').initialValue
      };
      if (fdRepairParams == 1 && (repairType == 1 || repairType == 'G')) {
        let fdRes = {};
        try {
          fdRes = await queryFdUploadStatusByRoNo(roNo);
        } catch (err) {
          console.log(err, '查询fd状态失败');
        }
        if (fdRes.resultCode == 200) {
          if (fdRes.data.FD_STATUS != 10041001) {
            return this.$notify.warning({
              title: '提示信息',
              message: '此工单未上传FD不允许打印委托书'
            });
          }
        }
      }

      this.$nextTick(() => {
        this.$refs.print.EXCUTE_PRINT();
      });
      // firstPrintRepairOrder(roNo);
      console.log(roNo);
    },
    // 字符串转驼峰
    camelcase(str) {
      let arr = str.split('_');
      let upper = arr.map((val, index) => {
        let lowStr = val.toLowerCase();
        if (index) {
          lowStr = lowStr.charAt(0).toLocaleUpperCase() + lowStr.slice(1);
        }
        return lowStr;
      });
      return upper.join('');
    },

    // 把返回的数据赋值给表单
    async syncFormListData(dataList) {
      const formList = [...this.topFilterList];
      const formFieldNames = formList.map(x => x.fieldName);
      dataList.forEach(x => {
        if (formFieldNames.includes(x.fieldName)) {
          let target = formList.find(k => k.fieldName === x.fieldName);
          if (!target) return;
          target.initialValue = x.value;
        }
        if (x.fieldName === 'endTimeSupposed') {
          // console.log(x, 'xxxxx');
          x.value && (this.topFilterList.find(x => x.fieldName === 'endTimeSupposed').initialValue = moment(x.value).format('YYYY-MM-DD HH:mm:ss'));
        }
      });
      // this.printBalance();
    },

    tabClickHandle(tab) {},

    closeDialog() {
      this.$emit('closeDialog');
    },

    isShows() {
      // console.log(this.list.RO_STATUS, 'list.RO_STATUS---');
      let result = false;
      if (this.list.RO_STATUS === 80491003 || this.list.RO_STATUS === 80491009) {
        result = true;
      }
      // console.log(result, 'result---');
      if (result) {
        this.queryPay();
        return result;
      }
    },

    // 打印结算单
    async printBalanceClick() {
      this.printBalanceData.RO_NO = this.list.RO_NO;
      this.printBalanceData.OWNER_NO = this.list.OWNER_NO;
      this.prePrintDialogShow = true;
    }
  }
};
</script>

<style lang="less" scoped>
.panel-heading {
  color: #34495e;
  background-color: #f5f5f5;
  border-color: #ddd;
  padding: 10px 15px;
  margin-bottom: 10px;
}
.model-footer {
  padding: 15px;
  margin-top: 50px;
  text-align: center;
  height: 40px;
  line-height: 40px;
}
</style>
